package com.ruoyi.project.monitor.tarsmonitor.task.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.monitor.tarsmonitor.domain.TarsMonitor;
import com.ruoyi.project.monitor.tarsmonitor.service.ITarsMonitorService;
import com.ruoyi.project.monitor.tarsmonitor.task.TarsMonitorTask;
import com.ruoyi.project.monitor.warndistribute.service.IWarnDistributeService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("tarsMonitor")
public class TarsMonitorTaskImpl implements TarsMonitorTask {

    @Autowired
    RuoYiConfig ruoYiConfig;

    @Autowired
    ITarsMonitorService iTarsMonitorService;

    @Autowired
    IWarnDistributeService iWarnDistributeService;

    public static void setStatus(String server, TarsMonitor monitor) {

        try {
            String s = HttpUtils.sendGet("http://api.youzhi.net/api/monitor/status", "server=" + server);
            JSONObject json = new JSONObject(s);
            int status = json.getInt("status");
            String msg = json.getString("message");
            monitor.setStatus(status);
            monitor.setMsg(msg);
        } catch (Exception e) {
            monitor.setStatus(500);
            monitor.setMsg(e.getMessage());
        }

    }

    @Override
    public void run() {

        if (!ruoYiConfig.isProd()) {
            return;
        }

        TarsMonitor query = new TarsMonitor();
        query.setEnable(1);
        List<TarsMonitor> list = iTarsMonitorService.selectTarsMonitorList(query);
        list.forEach(item -> {

            setStatus(item.getServer(), item);
            item.setLastStatusTime(DateUtils.getNowDate());
            iTarsMonitorService.updateTarsMonitor(item);

            if (item.getStatus() != 200) {
                iWarnDistributeService.onError("tars服务[" + item.getServer() + "]", "服务无法访问");
            }

        });
    }

    public static void main(String[] args) {

    }

}
